import { useEffect, useRef, useState } from 'react'

const useRequest = (api, defaultData, defaultParams = {}, onSuccess) => {
	const requestParamsRef = useRef(defaultParams)
	const [loading, setLoading] = useState(true)
	const [data, setData] = useState(defaultData)
	const [error, setError] = useState('')

	useEffect(() => {
		api(requestParamsRef.current)
			.then(data => {
				setData(data)
				setLoading(false)
				setError('')
				if (onSuccess) {
					onSuccess(data)
				}
			})
			.catch(e => {
				setLoading(false)
				setError(e.message)
			})
	}, [loading])

	return {
		data,
		loading,
		error,
		setLoading,
		setRequestParams: value => {
			requestParamsRef.current = { ...requestParamsRef.current, ...value }
		}
	}
}

export default useRequest
